<?php

/**
 * This is the model class for table "tbl_contracts".
 *
 * The followings are the available columns in table 'tbl_contracts':
 * @property string $contractid
 * @property string $custno
 * @property string $locno
 * @property integer $contractype
 * @property string $orginalcontractid
 * @property string $contractamount
 * @property string $contractstartdate
 * @property string $contractenddate
 * @property integer $salesperson
 * @property string $jobno
 * @property integer $billtype
 * @property integer $status
 * @property string $lastdatebilled
 * @property string $lastaccuralpostperiod
 * @property string $invoiceemail
 * @property string $purchasedby
 */
class Contracts extends CActiveRecord
{
    const TYPE_YEARLY=0;
    const TYPE_MONTHLY=1;
    const TYPE_QUARTERLY=2;

    /**
     * Returns the static model of the specified AR class.
     * @return Contracts the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'tbl_contracts';
    }

    public function getBillTypeList()
    {
        return array(
            self::TYPE_YEARLY => 'Yearly',
            self::TYPE_MONTHLY => 'Monthly',
            self::TYPE_QUARTERLY => 'Quarterly',
        );
    }

    public function getBillTypeText()
    {
        return isset($this->billTypeList[$this->billtype]) ? $this->billTypeList[$this->billtype] : NULL;
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('contractid, custno, locno, contractype, orginalcontractid, contractamount, contractstartdate, contractenddate, salesperson, jobno, billtype, lastdatebilled, lastaccuralpostperiod', 'safe'),
            array('contractype, billtype', 'numerical', 'integerOnly' => true),
            array('contractid, orginalcontractid, jobno', 'length', 'max' => 41),
            array('salesperson', 'length', 'max' => 4),
            array('custno', 'length', 'max' => 7),
            array('locno', 'length', 'max' => 5),
            array('invoiceemail', 'length', 'max' => 255),
            array('area1accountno,area1description', 'length', 'max' => 9999),
            array('contractamount', 'length', 'max' => 10),
            array('invoiceemail', 'email', 'allowEmpty' => true),
            array('purchasedby', 'length', 'max' => 50),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('contractid,status, custno, locno, contractype, orginalcontractid, contractamount, contractstartdate, contractenddate, salesperson, jobno, billtype, lastdatebilled, lastaccuralpostperiod', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'customer' => array(self::BELONGS_TO, 'Customers', 'custno'),
            'quarterlyPayments' => array(self::HAS_MANY, 'ContractQuarterly', 'contractid', 'order' => 'number'),
            'monthlyPayments' => array(self::HAS_MANY, 'ContractMonthly', 'contractid', 'order' => 'number'),
           // 'location' => array(self::BELONGS_TO, 'Locations', 'custno,locno'),
        );
    }
    public function getLocation(){
        return Locations::model()->find('custno=:custno AND locno=:locno',array(
            'custno'=>$this->custno,
            'locno'=>$this->locno
        ));
    }
    public function getQuoteList()
    {
        $list = Invoice::model()->findAll('agreementno=:agreementno AND invoicetype=:type', array(
            'agreementno' => $this->contractid,
            'type' => Invoice::TYPE_QUOTE
                ));
        return $list;
    }

    public function getInvoiceList()
    {
        $list = Invoice::model()->findAll('agreementno=:agreementno AND invoicetype=:type', array(
            'agreementno' => $this->contractid,
            'type' => Invoice::TYPE_INVOICE
                ));
        return $list;
    }

    public function getSalesOrdersList()
    {
        $list = Invoice::model()->findAll('agreementno=:agreementno AND invoicetype=:type', array(
            'agreementno' => $this->contractid,
            'type' => Invoice::TYPE_SALES_ORDERS
                ));
        return $list;
    }

    public function getPaymentScheduleList()
    {
        $schedule = null;
        if ($this->billtype == Contracts::TYPE_MONTHLY)
        {
            $schedule = $this->monthlyPayments;
        }
        else if ($this->billtype == Contracts::TYPE_QUARTERLY)
        {
            $schedule = $this->quarterlyPayments;
        }
        return $schedule;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'contractid' => 'Contract ID',
            'custno' => 'Customer',
            'locno' => 'Location',
            'contractype' => 'Contract type',
            'orginalcontractid' => 'Orginal contract ID',
            'contractamount' => 'Contract amount',
            'contractstartdate' => 'Contract start date',
            'contractenddate' => 'Contract end date',
            'salesperson' => 'Sales person',
            'jobno' => 'Job #',
            'billtype' => 'Bill type',
            'lastdatebilled' => 'Last date billed',
            'lastaccuralpostperiod' => 'Last accural post period',
            'area1accountno' => 'Area 1 Account No',
            'area1description' => 'Area 1 Description',
            'invoiceemail' => 'Email',
            'purchasedby' => 'Purchased by',
        );
    }

    public function getStatusText()
    {
        return isset($this->StatusFullList[$this->status]) ? $this->StatusFullList[$this->status] : NULL;
    }

    public function getStatusFullList()
    {
        $data = CHtml::listData(ContractStatus::model()->findAll('inactive=0'), 'id', 'description');
        if (count($data) > 0)
        {

            return $data;
        }
        return NULL;
    }

    public static function getLocalList($custno, $locno)
    {
        $list = Contracts::model()->findAll('custno=:custno AND locno=:locno', array(
            'custno' => $custno,
            'locno' => $locno
                ));
        return Html::listData($list, 'contractid', 'contractid', true);
    }

    public function saveQuarterlyPayment()
    {
        if ($this->billtype == self::TYPE_QUARTERLY)
        {
            $this->saveMonthlyQuarterlyPayment('tbl_contract_quarterly', 4, $this->contractid, $this->contractamount);
            return $this->getQuarterlyPayment();
        }
    }

    public function getQuarterlyPayment()
    {
        $rs = array();
        if ($this->billtype == self::TYPE_QUARTERLY)
        {
            $list = $this->quarterlyPayments;
            foreach ($list as $item)
            {
                $rs[] = $item->attributes;
            }
        }
        return $rs;
    }

    public function saveMonthlyPayment()
    {
        if ($this->billtype == self::TYPE_MONTHLY)
        {
            $this->saveMonthlyQuarterlyPayment('tbl_contract_monthly', 12, $this->contractid, $this->contractamount);
            return $this->getMonthlyPayment();
        }
    }

    public function getMonthlyPayment()
    {
        $rs = array();
        if ($this->billtype == self::TYPE_MONTHLY)
        {
            $list = $this->monthlyPayments;
            foreach ($list as $item)
            {
                $rs[] = $item->attributes;
            }
        }
        return $rs;
    }

    public function saveMonthlyQuarterlyPayment($table, $count, $contractid, $amount)
    {

        $part = round($amount / $count, 2, PHP_ROUND_HALF_DOWN);
        $odd = $amount - ($part * ($count - 1));
        $increment = 12 / $count;

        $curMonth = new DateTime($this->contractstartdate);

        for ($i = 1; $i <= $count; $i++)
        {
            $item = Yii::app()->db->createCommand('select * from ' . $table . ' where number=:i and contractid=:contractid')
                            ->bindValues(array(
                                'i' => $i,
                                'contractid' => $contractid
                            ))->queryRow();

            if ($item != NULL)
            {
                if ($i != 1)
                {
                    $curMonth->add(new DateInterval("P{$increment}M"));
                    $item['date'] = $curMonth->format('Y-m-d');
                }
                else
                {
                    $item['date'] = $this->contractstartdate;
                }
                $item['amount'] = $i != 4 ? $part : $odd;
                Yii::app()->db->createCommand()->update($table, $item, 'number=:i and contractid=:contractid', array(
                    'i' => $i,
                    'contractid' => $contractid
                        )
                );
            }
            else
            {
                $item['contractid'] = $contractid;
                $item['amount'] = $i != $count ? $part : $odd;
                if ($i != 1)
                {
                    $curMonth->add(new DateInterval("P{$increment}M"));
                    $item['date'] = $curMonth->format('Y-m-d');
                }
                else
                {
                    $item['date'] = $this->contractstartdate;
                }
                $item['number'] = $i;
                $item['invoice'] = '';
                Yii::app()->db->createCommand()->insert($table, $item);
            }
        }
    }

    public function createScheduleInvoiceItem($invoice, $amount)
    {
        $partno = 'C-' . ContractType::getText($this->contractype);
        $inv = Inventory::model()->findByPk($partno);
        $pricecode = Yii::app()->db->createCommand('select pricecode from tbl_customers where custno=:custno')
                        ->bindValues(array('custno' => $this->custno))->queryScalar();
        if ($inv != NULL)
        {



            $model = new InvoiceLedger();
            $model->warehouse = '0000';
            $model->partno = $partno;
            $model->description = $inv->description;
            $model->qty = 1;
            $model->cost = 0;
            $model->markupvalue = 190;
            $model->taxed = 0;
            $model->noprint = 0;
            $model->tax1 = 0;
            $model->invoice = $invoice;
            $model->price = $inv->getPrice($pricecode);
            $model->price+=$amount;

            if ($model->save())
            {
                return $model;
            }
        }


        return null;
    }
    public function createHISTItem(){
        if($this->billtype==self::TYPE_MONTHLY || $this->billtype==self::TYPE_QUARTERLY){
            $partno='HIST';
            $inv = Inventory::model()->findByPk($partno);
            $pricecode = Yii::app()->db->createCommand('select pricecode from tbl_customers where custno=:custno')
                            ->bindValues(array('custno' => $this->custno))->queryScalar();
            if ($inv != NULL)
            {

                $model = ContractLedger::model()->find('contractid=:contractid AND partno=:partno', array(
                    'partno' => $partno,
                    'contractid' => $this->contractid
                        ));

                if ($model == NULL)
                {
                    $model = new ContractLedger();
                    $model->warehouse = '0000';
                    $model->partno = $partno;
                    $model->contractid = $this->contractid;
                    $type = $this->getBillTypeText();
                    $model->description = "Bill Type: $type";
                    $model->qty = 1;
                    $model->cost = 0;
                    $model->markupvalue = 190;
                    $model->taxed = 0;
                    $model->noprint = 0;
                    $model->tax1 = 0;
                    $model->price = $inv->getPrice($pricecode);
                }       
                if ($model->save())
                {
                    return $model;
                }
            }
        }

        return null;
    }
    public function createCItem()
    {


        $partno = 'C-' . ContractType::getText($this->contractype);
        $inv = Inventory::model()->findByPk($partno);
        $pricecode = Yii::app()->db->createCommand('select pricecode from tbl_customers where custno=:custno')
                        ->bindValues(array('custno' => $this->custno))->queryScalar();
        if ($inv != NULL)
        {

            $model = ContractLedger::model()->find('contractid=:contractid AND partno=:partno', array(
                'partno' => $partno,
                'contractid' => $this->contractid
                    ));

            if ($model == NULL)
            {
                $model = new ContractLedger();
                $model->warehouse = '0000';
                $model->partno = $partno;
                $model->contractid = $this->contractid;
                $type = $this->getBillTypeText();
                $model->description = "1st $type Payment for Annual Service Contract No. $this->contractid";
                $model->qty = 1;
                $model->cost = 0;
                $model->markupvalue = 190;
                $model->taxed = 0;
                $model->noprint = 0;
                $model->tax1 = 0;
            }


            $model->price = $inv->getPrice($pricecode);
            $model->price+=$this->contractamount;

            if ($model->save())
            {
                return $model;
            }
        }


        return null;
    }

    public function canCreateFirstScheduleInvoice()
    {
        $schedule = $this->getPaymentScheduleList();
        if ($schedule == null)
        {
            return false;
        }
        else if (count($schedule) == 0)
        {
            return false;
        }
        $invoiceList = $this->getInvoiceList();
        if (count($invoiceList) == 0)
        {
            $salesOrderList = $this->getSalesOrdersList();
            $quoteList = $this->getQuoteList();
            if (count($salesOrderList) > 0 && count($quoteList) > 0)
            {
                return true;
            }
        }
        else
        {
            return false;
        }
        return false;
    }

    public function getNearestUnInvoicePayment()
    {
        return count($this->paymentScheduleList) > 0 ? $this->paymentScheduleList[0] : NULL;
    }
    public function deleteInvoiceFromSchedule($invoice){
        if($this->billtype==self::TYPE_MONTHLY){
            Yii::app()->db->createCommand()->delete('tbl_contract_monthly', 'contractid=:contractid AND invoice=:invoice',
                    array(
                        'contractid'=>$this->contractid,
                        'invoice'=>$invoice
                    ));
        }else if($this->billtype==self::TYPE_QUARTERLY){
            Yii::app()->db->createCommand()->delete('tbl_contract_quarterly', 'contractid=:contractid AND invoice=:invoice',
                    array(
                        'contractid'=>$this->contractid,
                        'invoice'=>$invoice
                    ));
            
        }
    }

}